import React, { useEffect, useState } from 'react';
import { Play, Pause, StopCircle, DropletIcon } from 'lucide-react';
import { useQuery } from '@tanstack/react-query';
import { dispenserApi } from '../../api/Api';
import { Order } from '../../types';
import { useHttp } from '../../hooks/useHttp';

interface SystemControlProps {
  onStart: (initRobotCount: number) => void;
  // onPause: () => void;
  onStop: () => void;
  aliveTime: number;
}

export function SystemControl({ onStart, onStop, aliveTime}: SystemControlProps) {
  const [initRobotCount, setInitRobotCount] = useState<number>(8);    //初始化机器人数量
  const [isRunning, setIsRunning] = useState<boolean>(false);   //系统是否运行

  // 监听 aliveTime 的变化，根据其值来控制 isRunning 的状态
  useEffect(() => {
    if (aliveTime === 0) {
      setIsRunning(false);  // 如果 aliveTime 为 0，表示系统未启动
    } else {
      setIsRunning(true);  // 如果 aliveTime 有值，表示系统正在运行
    }
  }, [aliveTime]);

  const handleStart = () => {
    onStart(initRobotCount); 
    // setIsRunning(true); 
  };

  const handleStop =() =>{
    onStop();
    // setIsRunning(false);
  }

  const handleRobotCountChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setInitRobotCount(Number(event.target.value)); 
  };


  // test
  const [deliveredOrderNumbers, setDeliveredOrderNumbers] = useState<string[]>([]);  // 用来记录已交付订单号

  const {
    data: orders = [],
    isLoading: isLoadingOrders,
  } = useQuery<Order[]>({
    queryKey: ['pendingOrders'],
    queryFn: dispenserApi.getPendingOrders,
  });

  //药品交付
  const handleDispenseMedication = async () => {
    const pendingOrderFirst = orders.find(       
      (order) => order.status === 0 && !deliveredOrderNumbers.includes(order.orderNumber)  // 过滤已交付订单
    );
    if (!pendingOrderFirst) return;

    // 更新已交付订单号数组
    setDeliveredOrderNumbers((prev) => [...prev, pendingOrderFirst.orderNumber]);

    // 执行交付操作, 发送订单号给后端
    const { sendPostRequest } = useHttp();
    const handleSendOrder = async (orderNum: string) => {
      try {
        const data = await sendPostRequest( { order_num: orderNum });
        console.log('http响应:', data);
      } catch (error) {
        console.error('http错误', error);
      }
    };
    // 调用 handleSendOrder 发送订单号
    await handleSendOrder(pendingOrderFirst.orderNumber);
  };

  return (
    <div className="bg-white p-4 rounded-lg shadow-md">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xl font-bold">系统控制</h2>
        <div className="flex gap-2">
          <button
            onClick={handleStart}
            disabled={isRunning} //已启动则禁用启动按钮
            className="p-2 bg-green-500 text-white rounded-md hover:bg-green-600 disabled:opacity-50"
          >
            <Play size={20} />
          </button>
{/* test */}
          <button
            onClick={handleDispenseMedication}
            className="p-2 bg-red-500 text-white rounded-md hover:bg-red-600 disabled:opacity-50"
          >
            <DropletIcon size={20} />
          </button>

          <button
            onClick={handleStop}
            disabled={!isRunning} //未启动则禁用停止按钮
            className="p-2 bg-red-500 text-white rounded-md hover:bg-red-600 disabled:opacity-50"
          >
            <StopCircle size={20} />
          </button>
        </div>
      </div>
      
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm font-medium text-gray-700">机器人数量</label>
          <input
            type="number"
            value={initRobotCount}
            onChange={handleRobotCountChange}
            className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
            min="1"
            disabled={isRunning} 
          />
        </div>
      </div>
    </div>
  );
}


